<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 搜索添加框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入用户名"
            v-model="usersInfo.query"
            @input="getUsersInfo"
            clearable
            @clear="getUsersInfo"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersInfo"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加商品按钮 -->
          <el-button type="primary" @click="addUserVisible = true"
            >添加用户</el-button
          >
        </el-col>
        <el-col :span="4">
          <!-- 获取所有用户信息 -->
          <el-button type="primary" @click="clearUsersQuert"
            >查看所有用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 内容表格区 -->
      <el-table :data="users" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <div>
              <!-- 使用作用域插槽获取状态值 -->
              <el-switch
                v-model="scope.row.mg_state"
                @change="changeState(scope.row)"
              >
              </el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <div>
              <el-tooltip content="编辑" placement="top" :enterable="false">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="changeUserInfo(scope.row.id)"
                ></el-button>
              </el-tooltip>

              <el-tooltip content="删除" placement="top" :enterable="false">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteUser(scope.row)"
                ></el-button>
              </el-tooltip>

              <el-tooltip content="分配角色" placement="top" :enterable="false">
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        class="users_page"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersInfo.pagenum"
        :page-sizes="[5, 7, 9, 10]"
        :page-size="usersInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserVisible"
      width="50%"
      @close="closeDiakog"
    >
      <!-- 添加用户的对话框文本内容 -->
      <el-form
        :model="addUserObj"
        :rules="addUserRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserObj.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserObj.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserObj.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserObj.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部确认与取消 -->
      <span slot="footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsersGetInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户的对话框文本内容 -->
    <el-dialog
      title="编辑"
      :visible.sync="changeDialogVisible"
      width="50%"
      @close="closeChangeDialog"
    >
      <!-- 内容区 -->
      <el-form
        ref="changeFormRef"
        :model="changeFormObj"
        label-width="80px"
        :rules="addUserRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="changeFormObj.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="changeFormObj.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="changeFormObj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部确认区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureChangeUserInfo(changeFormObj.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

      <!-- 分配角色会话框 -->
    <el-dialog
    @close="closeSetRoleDialog"
  title="分配角色"
  :visible.sync="setRolesDialog"
  width="50%">
  <div class="setRoleStytle">
    <p>当前的用户：{{setRoleRow.username}}</p>
    <p>当前的角色：{{setRoleRow.role_name}}</p>
    <p>分配新角色：
      <!-- 选择框 -->
 <el-select v-model="setRoleValue" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>

    </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRolesDialog = false">取 消</el-button>
    <el-button type="primary" @click="sureSetNewRole">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail =
        /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }
      // 不合法的邮箱
      cb(new Error("请输入合法的邮箱"));
    };

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (regMobile.test(value)) {
        // 合法手机号
        return cb();
      }
      // 不合法手机号
      cb(new Error("请输入合法手机号"));
    };

    return {
      usersInfo: {
        // 搜索关键字
        query: "",

        // 当前页数
        pagenum: 1,

        // 当前页的数据个数
        pagesize: 5,
      },
      // 用户数据对象
      users: [],

      // 总用户数据数
      total: 0,

      // 是否显示用户添加的对话框
      addUserVisible: false,

      // 添加用户的信息
      addUserObj: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },

      // 是否显示编辑用户的对话框
      changeDialogVisible: false,

      // 点击分配角色存放的一整行数据，给会话框使用
      setRoleRow:{},

      // 编辑用户的对话框的表单,存储用id获取到的数据
      changeFormObj: {
        username: "",
        email: "",
        mobile: "",
        id: "",
      },

      // 分配角色会话框是否可见
      setRolesDialog:false,

      // 分配角色会话框里面的选择框双向绑定的数据
      setRoleValue:'',
      // 获取角色列表
      rolesList:[],

      // 添加用户会话框表单验证
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },

      // 编辑会话框表单的校验直接复用addUserRules的规则
      // 编辑会话框表单校验规则
      // changeUserRules:{
      //   username:[ { required: true, message: "请输入用户名", trigger: "blur" },
      //     { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },],
      // },
    };
  },
  methods: {
    // 获取所有用户信息
    async getUsersInfo() {
      let { data: res } = await this.$http({
        url: "users",
        method: "get",
        params: this.usersInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("请求出错");
      this.users = res.data.users;
      this.total = res.data.total;
    },

    // 清除搜索框，显示所有
    clearUsersQuert() {
      this.usersInfo.query = "";
      this.getUsersInfo();
    },

    // 改变每页的数据数
    handleSizeChange(newValue) {
      this.usersInfo.pagesize = newValue;
      this.getUsersInfo();
    },

    // 改变当前页
    handleCurrentChange(newValue) {
      this.usersInfo.pagenum = newValue;
      this.getUsersInfo();
    },

    // 修改用户状态
    async changeState(rowInfo) {
      // 修改用户状态请求
      const { data: res } = await this.$http.put(
        `users/${rowInfo.id}/state/${rowInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        rowInfo.mg_state = !rowInfo.mg_state;
        return this.$message.error("更新用户状态失败");
      } else {
        return this.$message.success("更新用户状态成功");
      }
    },

    // 关闭会话框触发的方法
    closeDiakog() {
      //重置表单
      this.$refs.addFormRef.resetFields();
    },

    // 添加用户会话框点击确定后的方法
    addUsersGetInfo() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          let { data: res } = await this.$http.post("users", this.addUserObj);
          if (res.meta.status !== 201) {
            this.addUserVisible = false;
            return this.$message.error("添加用户失败");
          }
          this.getUsersInfo();
          this.addUserVisible = false;
        }
      });
    },

    // 编辑按钮
    async changeUserInfo(id) {
      this.changeDialogVisible = true;
      let { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取信息失败");
      }
      this.changeFormObj = res.data;
    },

    // 编辑按钮 确定修改
    sureChangeUserInfo(id) {
      this.$refs.changeFormRef.validate(async (valid) => {
        if (valid) {
          let { data: res } = await this.$http.put(`users/${id}`, {
            email: this.changeFormObj.email,
            mobile: this.changeFormObj.mobile,
          });
          if (res.meta.status !== 200) {
            this.changeDialogVisible = false;
            return this.$message.error("更新数据失败");
          }
          this.getUsersInfo();
          this.changeDialogVisible = false;
          this.$message.success("更新数据成功");
        }
      });
    },

    // 关闭编辑用户对话框后的方法   初始化表单
    closeChangeDialog() {
      //重置表单
      this.$refs.changeFormRef.resetFields();
    },

    // 删除单个用户
    async deleteUser(row) {
      const confirmResult = await this.$confirm(
        `此操作将永久删除该用户:${row.username}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        this.$message.info("已取消删除");
      });
      if (confirmResult == "confirm") {
        let { data: res } = await this.$http.delete(`users/${row.id}`);
        if (res.meta.status !== 200) {
          return this.$message.error("删除用户失败");
        } else {
          this.getUsersInfo();
          return this.$message.success("删除用户成功");
        }
      }
    },

    // 分配角色
    async setRole(row){
      this.setRoleRow = row
      const {data:res} = await this.$http.get('roles')
      if(res.meta.status !== 200){this.$message.error('请求数据失败')}
      else{this.rolesList = res.data}
      this.setRolesDialog = true
    },

    // 确定分配角色
    async sureSetNewRole(){
      const {data:res} = await this.$http.put(`users/${this.setRoleRow.id}/role`,{rid:this.setRoleValue})
      if(res.meta.status !== 200){
        this.$message.error('分配角色失败')
      }else{
        this.getUsersInfo()
        this.$message.success("分配角色成功")
      }
      this.setRolesDialog = false
    },

    // 关闭分配角色会话框
    closeSetRoleDialog(){
      this.setRoleValue='',
      this.setRoleRow={}
    },
  },
  mounted() {
    this.getUsersInfo();
  },
};
</script>

<style lang="less" scoped>
.users_page {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}
</style>